/*
 * @lc app=leetcode.cn id=82 lang=cpp
 *
 * [82] 删除排序链表中的重复元素 II
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
    ListNode *deleteDuplicates(ListNode *head)
    {
        if (!head)
            return nullptr;
        map<int, int> m;

        ListNode *tmp = head;
        while (tmp)
        {
            m[tmp->val]++;
            tmp = tmp->next;
        }

        while (head && m[head->val] > 1)
        {
            head = head->next;
        }

        ListNode *ans = head;

        while (head && head->next)
        {
            while (head->next && m[head->next->val] > 1)
            {
                head->next = head->next->next;
            }
            head = head->next;
        }
        return ans;
    }
};
// @lc code=end
